package com.ftf.tp.blog.infrastructure.repository;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ftf.tp.blog.domain.article.dos.QuestionPageDO;
import com.ftf.tp.blog.domain.configuration.aggregate.QuestionAgg;
import com.ftf.tp.blog.domain.configuration.dos.QuestionDO;
import com.ftf.tp.blog.domain.configuration.repository.QuestionRepository;
import com.ftf.tp.blog.infrastructure.converter.QuestionConvert;
import com.ftf.tp.blog.infrastructure.mapper.QuestionMapper;
import com.ftf.tp.blog.infrastructure.mapper.QuestionTagMapper;
import com.ftf.tp.blog.infrastructure.mapper.pos.QuestionPO;
import com.ftf.tp.blog.infrastructure.mapper.pos.QuestionTag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author tanghao
 * @date 2022/8/11
 */
@Slf4j
@Repository
public class QuestionRepositoryImpl implements QuestionRepository {

    @Resource
    private QuestionMapper questionMapper;

    @Resource
    private QuestionTagMapper questionTagMapper;

    /**
     * 提问入库
     *
     * @param questionAgg 问题聚合
     */
    @Override
    public void save(QuestionAgg questionAgg) {
        questionMapper.insert(QuestionConvert.INSTANCE.toPo(questionAgg));
        questionTagMapper.batchInsert(questionAgg.getTagValues().stream()
                .map(tagValue -> QuestionTag.builder()
                        .questionId(questionAgg.getId())
                        .tagId(tagValue.getId())
                        .tagName(tagValue.getTagName()).build()).collect(Collectors.toList()));
    }

    /**
     * 问题分页
     *
     * @param questionPageDO 分页参数
     * @return 分页结果
     */
    @Override
    public List<QuestionDO> pageQuestion(QuestionPageDO questionPageDO) {
        QueryWrapper<QuestionPO> queryWrapper = new QueryWrapper<>();
        if (questionPageDO.getHot()) {
            queryWrapper.orderByDesc("hot_nums");
        }
        if (questionPageDO.getLatest()) {
            queryWrapper.orderByDesc("created_time");
        }
        if (questionPageDO.getInvitation()) {
            //todo 邀请问题分页
            List<Long> idList = questionMapper.randId(questionPageDO.getSize());
            queryWrapper.in("id", idList);
        }
        if (questionPageDO.getRecommend()) {
            //todo 推荐问题分页
            List<Long> idList = questionMapper.randId(questionPageDO.getSize());
            queryWrapper.in("id", idList);
        }
        Page<QuestionPO> questionPoPage = questionMapper.selectPage(
                new Page<>(questionPageDO.getPage(), questionPageDO.getSize()), queryWrapper);
        List<QuestionPO> questionPoList = questionPoPage.getRecords();
        return QuestionConvert.INSTANCE.toDOList(questionPoList);
    }
}
